package com.member.mp.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.member.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GenerateQR {

    /**
     * 生成二维码的方法
     *
     * @param content 二维码内容
     */
    public static String code(String content) {
        //设置二维码宽
        int width = 400;
        //设置二维码高
        int height = 400;
        //设置二维码的后缀名称
        String format = "png";
        //设置map集合要往二维码内添加的参数
        Map<EncodeHintType, Object> map = new HashMap<EncodeHintType, Object>();
        //设置二维码的级别
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //设置二维码中文本的编码格式
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置二维码的外边框
        map.put(EncodeHintType.MARGIN, 5);
        try {
            //创建生成二维码对象，调用方法将所需要的参数放入
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
            //创建path对象将物理地址放到file文件内，然后生成path对象
            Path path = Paths.get("./", format);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);
            File file = path.toFile();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            int n;
            while ((n = inputFile.read(buffer)) != -1) {
                bos.write(buffer, 0, n);
            }
            buffer = bos.toByteArray();
            String imageBase64 = Base64.getEncoder().encodeToString(buffer);
            inputFile.close();
            if (file.exists()) {
                file.deleteOnExit();
            }
            return imageBase64;
        } catch (WriterException | IOException e) {
            log.error("生成二维码错误，{}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }
}
